import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { cn } from '../lib/utils';
import { publicApi, ApiResponse } from '../services/api';
import { MilkdownPreview } from '../components/MilkdownPreview';
import { useTheme } from '../hooks/useTheme';

interface DocumentNode {
  id: string;
  name: string;
  type: 'folder' | 'file';
  children?: DocumentNode[];
  content?: string;
  isExpanded?: boolean;
  hasChild?: boolean;
  createUser?: string;
  createTime?: string;
  updateUser?: string;
  updateTime?: string;
}

interface DirectoryItem {
  id: string;
  name: string;
  pid: string;
  hasChild: boolean;
}

interface DocumentItem {
  docId: string;
  docTitle: string;
}

export default function ProjectShare() {
  const { teamId, id: projectId } = useParams<{ teamId: string; id: string }>();
  const navigate = useNavigate();
  const { isDark, toggleTheme } = useTheme();
  
  const [documents, setDocuments] = useState<DocumentNode[]>([]);
  const [selectedDoc, setSelectedDoc] = useState<DocumentNode | null>(null);
  const [content, setContent] = useState<string>('');
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [projectName, setProjectName] = useState<string>('');
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);
  const [hoveredNodeId, setHoveredNodeId] = useState<string>('');
  const [selectedFont, setSelectedFont] = useState('inter');
  
  const leftPanelRef = useRef<HTMLDivElement>(null);
  const rightPanelRef = useRef<HTMLDivElement>(null);

  const fontOptions = [
    { value: 'inter', label: 'Inter' },
    { value: 'serif', label: 'Serif' },
    { value: 'mono', label: 'Mono' }
  ];

  // 获取项目信息
  useEffect(() => {
    const fetchProjectInfo = async () => {
      console.log('ProjectShare: 开始获取项目信息', { projectId, teamId });
      if (!projectId || !teamId) {
        console.log('ProjectShare: 缺少 projectId 或 teamId');
        return;
      }
      
      try {
        console.log('ProjectShare: 调用 /doc/project/getProjectInfo 接口');
        const res: ApiResponse = await publicApi({
          url: '/doc/project/getProjectInfo',
          method: 'post',
          data: { projectId }
        });
        
        console.log('ProjectShare: 项目信息接口响应', res);
        if (res.code === 200) {
          setProjectName(res.data.projectName || '未命名项目');
        }
      } catch (err) {
        console.error('获取项目信息失败:', err);
      }
    };

    fetchProjectInfo();
  }, [projectId, teamId]);

  // 获取目录和文档列表
  useEffect(() => {
    const fetchDirectories = async () => {
      console.log('ProjectShare: 开始获取目录和文档列表', { projectId, teamId });
      if (!projectId || !teamId) {
        console.log('ProjectShare: 缺少 projectId 或 teamId');
        return;
      }
      
      setIsLoading(true);
      setError(null);
      
      try {
        console.log('ProjectShare: 调用 /doc/directory/getChildDirectoryAndDocList 接口');
        const res: ApiResponse = await publicApi({
          url: '/doc/directory/getChildDirectoryAndDocList',
          method: 'post',
          data: {
            directoryId: '0',
            projectId,
            teamId
          }
        });

        console.log('ProjectShare: 目录接口响应', res);
        if (res.code === 200) {
          // 转换接口数据为本地数据结构
          const childDirectoryList = res.data?.childDirectoryList || [];
          const childDocumentList = res.data?.childDocumentList || [];

          console.log('ProjectShare: 解析到的目录和文档', { childDirectoryList, childDocumentList });

          const directories = childDirectoryList.map((dir: DirectoryItem) => ({
            id: dir.id,
            name: dir.name,
            type: 'folder',
            isExpanded: false,
            hasChild: dir.hasChild,
            children: []
          }));

          const documents = childDocumentList.map((doc: DocumentItem) => ({
            id: doc.docId,
            name: doc.docTitle,
            type: 'file',
            content: '# 新文档'
          }));

          setDocuments([...directories, ...documents]);
        } else {
          setError(res.message || '获取目录失败');
        }
      } catch (err) {
        console.error('获取目录失败:', err);
        setError('网络错误，请稍后重试');
      } finally {
        setIsLoading(false);
      }
    };

    fetchDirectories();
  }, [projectId, teamId]);

  // 处理文档选择
  const handleDocSelect = async (doc: DocumentNode) => {
    if (doc.type !== 'file') return;
    
    setSelectedDoc(doc);
    setContent(doc.content || '# 新文档');
    
    // 获取文档内容
    try {
      const res: ApiResponse = await publicApi({
        url: '/doc/getDocByDocId',
        method: 'post',
        data: { docId: doc.id }
      });
      
      if (res.code === 200) {
        const updatedDoc = {
          ...doc,
          content: res.data?.docContent || '',
          createUser: res.data?.createUser,
          createTime: res.data?.createTime,
          updateUser: res.data?.updateUser,
          updateTime: res.data?.updateTime
        };
        setSelectedDoc(updatedDoc);
        setContent(res.data?.docContent || '');
      } else {
        setContent('# 获取文档内容失败');
      }
    } catch (err) {
      console.error('获取文档内容失败:', err);
      setContent('# 获取文档内容失败');
    }
  };

  // 辅助函数：查找节点
  const findNode = (nodes: DocumentNode[], id: string): DocumentNode | null => {
    for (const node of nodes) {
      if (node.id === id) return node;
      if (node.children) {
        const found = findNode(node.children, id);
        if (found) return found;
      }
    }
    return null;
  };

  // 辅助函数：为节点添加子节点
  const addChildrenToNode = (nodes: DocumentNode[], parentId: string, children: DocumentNode[]): DocumentNode[] => {
    return nodes.map(node => {
      if (node.id === parentId) {
        return {
          ...node,
          children: [...children]
        };
      }
      if (node.children) {
        return {
          ...node,
          children: addChildrenToNode(node.children, parentId, children)
        };
      }
      return node;
    });
  };

  // 辅助函数：更新节点属性
  const updateNodeProperty = (
    nodes: DocumentNode[], 
    id: string, 
    property: keyof DocumentNode, 
    value: any
  ): DocumentNode[] => {
    return nodes.map(node => {
      if (node.id === id) {
        return { ...node, [property]: value };
      }
      if (node.children) {
        return {
          ...node,
          children: updateNodeProperty(node.children, id, property, value)
        };
      }
      return node;
    });
  };

  // 处理文件夹点击
  const handleFolderClick = async (nodeId: string, currentExpanded: boolean) => {
    // 获取节点信息
    const node = findNode(documents, nodeId);
    if (!node || node.type !== 'folder') return;

    // 如果是要展开文件夹，且还没有加载过子目录数据
    if (!currentExpanded && node.hasChild && (!node.children || node.children.length === 0)) {
      try {
        console.log('ProjectShare: 展开文件夹，加载子目录数据', { nodeId, projectId, teamId });
        const res: ApiResponse = await publicApi({
          url: '/doc/directory/getChildDirectoryAndDocList',
          method: 'post',
          data: {
            directoryId: nodeId,
            projectId,
            teamId
          }
        });

        console.log('ProjectShare: 子目录接口响应', res);
        if (res.code === 200) {
          const childDirectoryList = res.data?.childDirectoryList || [];
          const childDocumentList = res.data?.childDocumentList || [];

          console.log('ProjectShare: 解析到的子目录和文档', { childDirectoryList, childDocumentList });

          // 转换目录数据
          const directories = childDirectoryList.map((dir: DirectoryItem) => ({
            id: dir.id,
            name: dir.name,
            type: 'folder',
            isExpanded: false,
            hasChild: dir.hasChild,
            children: []
          }));

          // 转换文档数据
          const docs = childDocumentList.map((doc: DocumentItem) => ({
            id: doc.docId,
            name: doc.docTitle,
            type: 'file',
            content: '# 新文档'
          }));

          // 合并目录和文档，保持原有顺序
          const children = [...directories, ...docs].sort((a, b) => {
            // 目录排在前面
            if (a.type === 'folder' && b.type !== 'folder') return -1;
            if (a.type !== 'folder' && b.type === 'folder') return 1;
            return 0;
          });

          // 更新树形结构，添加子节点并设置展开状态
          const updatedDocuments = addChildrenToNode(documents, nodeId, children);
          const finalDocuments = updateNodeProperty(updatedDocuments, nodeId, 'isExpanded', true);
          setDocuments(finalDocuments);
          
          // 自动选中第一个文档（如果有）
          if (docs.length > 0) {
            handleDocSelect(docs[0]);
          }
        } else {
          console.error('获取子目录失败:', res.message);
        }
      } catch (error: any) {
        console.error('获取子目录失败:', error);
      }
    } else {
      // 如果只是切换展开状态（收起或展开已加载的文件夹），直接更新状态
      const updateNode = (nodes: DocumentNode[], targetId: string): DocumentNode[] => {
        return nodes.map(node => {
          if (node.id === targetId) {
            // 切换当前节点的展开状态
            const newExpanded = !currentExpanded;
            
            // 如果是要收起，则递归收起所有子目录
            const newChildren = newExpanded 
              ? node.children 
              : node.children?.map(child => ({
                  ...child,
                  isExpanded: false,
                  children: child.children ? collapseAll(child.children) : []
                }));
                
            return {
              ...node,
              isExpanded: newExpanded,
              children: newChildren
            };
          }
          
          // 递归处理子节点
          if (node.children) {
            return {
              ...node,
              children: updateNode(node.children, targetId)
            };
          }
          
          return node;
        });
      };

      // 辅助函数：递归收起所有子目录
      const collapseAll = (nodes: DocumentNode[]): DocumentNode[] => {
        return nodes.map(node => {
          if (node.type === 'folder') {
            return {
              ...node,
              isExpanded: false,
              children: node.children ? collapseAll(node.children) : []
            };
          }
          return node;
        });
      };

      setDocuments(prev => updateNode(prev, nodeId));
    }
  };

  // 渲染文档树
  const renderDocumentTree = (nodes: DocumentNode[], depth = 0) => {
    return (
      <div className="space-y-1">
        {nodes.map(node => (
            <div 
              className="relative group" 
              key={node.id}
              onMouseEnter={() => setHoveredNodeId(node.id)}
              onMouseLeave={() => {
                // 延迟清除悬停状态，避免子目录展开时立即清除
                setTimeout(() => {
                  setHoveredNodeId(prev => prev === node.id ? '' : prev);
                }, 100);
              }}
            >
              <motion.div
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                onClick={(e) => {
                  e.stopPropagation();
                  if (node.type === 'folder') {
                    handleFolderClick(node.id, node.isExpanded || false);
                  } else {
                    handleDocSelect(node);
                    setContent(node.content || '# 新文档');
                  }
                }}
                className={cn(
                  "flex items-center px-3 py-2 rounded-md cursor-pointer transition-colors",
                  selectedDoc?.id === node.id 
                    ? (isDark ? "bg-blue-900" : "bg-blue-100")
                    : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                )}
                style={{ paddingLeft: `${depth * 12 + 12}px` }}
              >
              <div className="flex items-center flex-1 min-w-0">
                <div className="flex items-center w-6 justify-center">
                  {node.type === 'folder' && node.hasChild && (
                    <motion.i 
                      className={cn(
                        "fa-solid fa-chevron-right text-xs",
                        isDark ? "text-blue-300" : "text-orange-400",
                        node.isExpanded && "transform rotate-90"
                      )}
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      transition={{ duration: 0.2 }}
                    ></motion.i>
                  )}
                </div>
                  <motion.i 
                    className={cn(
                      node.type === 'folder' ? "fa-solid fa-folder" : "fa-solid fa-file-lines",
                      "w-5 text-center",
                      isDark ? "text-blue-400" : "text-orange-500",
                      node.type === 'folder' && !node.hasChild && "opacity-70"
                    )}
                    whileTap={{
                      rotate: 15
                    }}
                    transition={{
                      type: "spring",
                      stiffness: 300,
                      damping: 10
                    }}
                  ></motion.i>
                <span className="font-mono flex-1 ml-2 break-words">{node.name}</span>
              </div>
              </motion.div>
            
            {node.type === 'folder' && node.isExpanded && node.children && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                exit={{ opacity: 0, height: 0 }}
                transition={{ duration: 0.2 }}
                className="overflow-hidden"
              >
                {renderDocumentTree(node.children, depth + 1)}
              </motion.div>
            )}
          </div>
        ))}
      </div>
    );
  };

  // 设置初始加载完成状态
  useEffect(() => {
    if (!isLoading && documents.length > 0) {
      setInitialLoadComplete(true);
    }
  }, [isLoading, documents]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900">
      {/* 顶部导航栏 */}
      <header className={cn(
        "sticky top-0 z-50 backdrop-blur-md border-b transition-colors duration-200",
        isDark ? "bg-gray-800/90 border-gray-700" : "bg-white/90 border-gray-200"
      )}>
        <div className="max-w-6xl mx-auto px-4 py-3">
          <div className="flex items-center justify-between">
            {/* 左侧：项目信息 */}
            <div className="flex items-center space-x-4">
              <button
                onClick={() => navigate('/')}
                className={cn(
                  "flex items-center space-x-2 px-3 py-2 rounded-md transition-colors",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-arrow-left"></i>
                <span>返回首页</span>
              </button>
              <div className="h-6 w-px bg-gray-300 dark:bg-gray-600"></div>
              <div>
                <h1 className="font-mono font-bold text-lg">{projectName}</h1>
                <p className="text-sm text-gray-500">项目分享</p>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              {/* 字体选择 */}
              <div className="flex items-center space-x-2">
                <label className={cn(
                  "text-sm font-medium",
                  isDark ? "text-gray-300" : "text-gray-700"
                )}>
                  字体:
                </label>
                <select
                  value={selectedFont}
                  onChange={(e) => setSelectedFont(e.target.value)}
                  className={cn(
                    "px-2 py-1 rounded-md border text-sm transition-colors",
                    isDark 
                      ? "bg-gray-700 border-gray-600 text-gray-300 hover:bg-gray-600" 
                      : "bg-white border-gray-300 text-gray-700 hover:bg-gray-50"
                  )}
                >
                  {fontOptions.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>

              {/* 主题切换按钮 */}
              <button 
                onClick={toggleTheme}
                className={cn(
                  "w-10 h-10 rounded-full flex items-center justify-center",
                  isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
                )}
              >
                <i className={isDark ? "fa-solid fa-sun" : "fa-solid fa-moon"}></i>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* 主内容区域 - 占据剩余高度 */}
      <main className="flex-1 flex items-start bg-transparent h-[calc(100vh-64px)] min-h-0">
        <div className="mx-auto max-w-6xl w-full flex h-full min-h-0">
          {/* 左侧文档目录 - 独立滚动 */}
          <div 
            className={cn(
              "w-80 flex-shrink-0 backdrop-blur-md overflow-hidden rounded-xl shadow-md h-full min-h-0",
              isDark ? "bg-gray-800/90" : "bg-white/90"
            )}
            style={{ minWidth: '280px' }}
            ref={leftPanelRef}
          >
            <div className="h-full overflow-y-auto min-h-0">
              <div className="p-4">
                <div className="flex justify-between items-center mb-4">
                  <h2 className="font-mono font-bold">文档目录</h2>
                  {isLoading ? (
                    <i className="fa-solid fa-spinner fa-spin"></i>
                  ) : error ? (
                    <button 
                      onClick={() => window.location.reload()}
                      className="text-sm text-red-500 hover:underline"
                    >
                      重试
                    </button>
                  ) : (
                    <div className="flex space-x-1">
                      {/* 分享页面不显示添加按钮 */}
                    </div>
                  )}
                </div>
                {isLoading ? (
                  <div className="flex items-center justify-center h-32">
                    <i className="fa-solid fa-spinner fa-spin text-xl mr-2"></i>
                    <span>加载中...</span>
                  </div>
                ) : error ? (
                  <div className="text-red-500 p-4 text-center">
                    <p>{error}</p>
                    <button 
                      onClick={() => window.location.reload()}
                      className="mt-2 px-3 py-1 rounded-md text-sm bg-gray-200 hover:bg-gray-300"
                    >
                      重试
                    </button>
                  </div>
                ) : documents.length === 0 ? (
                  <div className="text-gray-500 p-4 text-center">
                    <p>暂无文档</p>
                  </div>
                ) : (
                  renderDocumentTree(documents)
                )}
              </div>
            </div>
          </div>

          {/* 分界线 */}
          <div 
            className={cn(
              "w-1.5 cursor-col-resize flex-shrink-0 rounded bg-gray-300 dark:bg-gray-700 transition-colors duration-200",
              "hover:bg-blue-400 dark:hover:bg-blue-500"
            )}
            style={{ minHeight: '480px', margin: '0 0' }}
            onMouseDown={(e) => {
              e.preventDefault();
              const startX = e.clientX;
              const startLeftWidth = leftPanelRef.current?.clientWidth || 320;
              const containerWidth = leftPanelRef.current?.parentElement?.clientWidth || 1200;
              
              const handleMouseMove = (moveEvent: MouseEvent) => {
                const dx = moveEvent.clientX - startX;
                const newLeftWidth = Math.max(280, Math.min(600, startLeftWidth + dx));
                
                // 确保右侧面板有足够的最小宽度
                const availableWidth = containerWidth - newLeftWidth - 6; // 6px for divider
                const newRightWidth = Math.max(300, availableWidth);
                
                if (leftPanelRef.current) {
                  leftPanelRef.current.style.width = `${newLeftWidth}px`;
                }
                if (rightPanelRef.current) {
                  rightPanelRef.current.style.minWidth = `${newRightWidth}px`;
                  rightPanelRef.current.style.width = `${newRightWidth}px`;
                }
              };

              const handleMouseUp = () => {
                document.removeEventListener('mousemove', handleMouseMove);
                document.removeEventListener('mouseup', handleMouseUp);
              };

              document.addEventListener('mousemove', handleMouseMove);
              document.addEventListener('mouseup', handleMouseUp);
            }}
          />

          {/* 右侧文档预览区 - 居中卡片美化 */}
          <div className="flex-1 flex items-start min-w-[300px] h-full min-h-0" ref={rightPanelRef}>
            {selectedDoc ? (
              <div className="flex flex-col h-full w-full">
                {/* 文档操作栏 - 固定在顶部 */}
                <div className={cn(
                  "flex-shrink-0 flex justify-between items-center p-2 border-b backdrop-blur-md rounded-t-xl",
                  isDark ? "bg-gray-800/90 border-gray-700" : "bg-white/90 border-gray-200"
                )}>
                  <div>
                    <h3 className="font-mono text-lg font-bold">{selectedDoc.name}</h3>
                    {/* 文档元信息 */}
                    <div className="text-xs text-gray-500 mt-1 flex flex-wrap gap-x-4 gap-y-1">
                      <span>创建人：{selectedDoc.createUser || '-'}</span>
                      <span>创建时间：{selectedDoc.createTime ? new Date(selectedDoc.createTime).toLocaleString('zh-CN') : '-'}</span>
                      {selectedDoc.updateUser && (
                        <span>更新人：{selectedDoc.updateUser}</span>
                      )}
                      {selectedDoc.updateTime && (
                        <span>最后更新时间：{new Date(selectedDoc.updateTime).toLocaleString('zh-CN')}</span>
                      )}
                    </div>
                  </div>
                </div>
                {/* 文档预览区域 - 卡片美化 */}
                <div className={cn(
                  "flex-1 h-full overflow-y-auto rounded-b-xl min-h-0",
                  isDark ? "bg-gray-900/80" : "bg-white/90"
                )}>
                  <div className="p-6 max-w-3xl mx-auto">
                    {initialLoadComplete ? (
                      <MilkdownPreview 
                        content={content || "请编辑文档内容"}
                        isDark={isDark}
                        className="text-base"
                        selectedFont={selectedFont}
                        data-preview="true"
                      />
                    ) : (
                      <div className="flex items-center justify-center h-full">
                        <i className="fa-solid fa-spinner fa-spin text-2xl mr-2"></i>
                        <span>加载文档内容中...</span>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ) : (
              <div className={cn(
                "flex items-center justify-center h-full w-full rounded-xl shadow-lg p-8 backdrop-blur-md",
                isDark ? "bg-gray-900/80" : "bg-white/90"
              )}>
                <p className="text-gray-500">请选择文档进行预览</p>
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
} 